package com.jyy.prefabricated.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.MakeUpExamDto;
import com.jyy.prefabricated.dto.PayOrderDto;
import com.jyy.prefabricated.dto.PayTypeDto;
import com.jyy.prefabricated.dto.StudentSignUpApplyDto;
import com.jyy.prefabricated.entity.StudentSignUpApply;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.enums.RegistrationTypeEnum;
import com.jyy.prefabricated.enums.StudentSignUpApplyStatusEnum;
import com.jyy.prefabricated.enums.SubjectStatusEnum;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.service.StudentSignUpApplyService;
import com.jyy.prefabricated.utils.ExcelUtil;
import com.jyy.prefabricated.utils.UserUtils;
import com.jyy.prefabricated.vo.CerticateVo;
import com.jyy.prefabricated.vo.StudentSignUpApplyVo;
import junit.framework.Test;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 学员报名申请
 *
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class StudentSignUpApplyController {

    @Autowired
    private StudentSignUpApplyService applyService;

    @Autowired
    private UserUtils userUtils;


    /**
     * 新增申请（学员报名）
     *
     * @param apply
     * @return
     */
    @PostMapping("/student-sign-up-apply")
    public AjaxResult insert(@Valid @RequestBody StudentSignUpApply apply) {
        log.info("Rest request to insert student-sign-up-apply:{}", apply);
        int id = applyService.insert(apply);
        if (id == -1) {
            return AjaxResult.error("当前站点人数已满，请重新选择站点或等待该站点下一期考试", -1);
        }
        if (id == -2) {
            return AjaxResult.error("报名该项目已超过2年，不允许再报考", -2);
        }
        return AjaxResult.success();
    }

    /**
     * 新增申请（学员导入报名）
     *
     * @param file
     * @return
     */
    @PostMapping("/student-sign-up-apply/{projectId}")
    public AjaxResult insert(@PathVariable Integer projectId, MultipartFile file) {

        int id = applyService.insert(file, projectId);
        if (id == -1) {
            return AjaxResult.error(-1, "导入学员信息为空");
        }
        if (id == -2) {
            return AjaxResult.error(-2, "报名该项目已超过2年，不允许再报考");
        }
        if (id == -3) {
            return AjaxResult.error(-3, "导入信息不完整，请核对");
        }
        return AjaxResult.success();
    }

    /**
     * 修改申请
     *
     * @param apply
     * @return
     */
    @PutMapping("/student-sign-up-apply")
    public AjaxResult update(@Valid @RequestBody StudentSignUpApply apply) {
        log.info("Rest request to update student-sign-up-apply:{}", apply);
        int id = applyService.update(apply);
        if (id == -1) {
            return AjaxResult.error(-1, "当前站点人数已满，请重新选择站点或等待该站点下一期考试");
        }
        StudentSignUpApplyVo result = applyService.selectById(apply.getId());
        return AjaxResult.success(result);
    }

    /**
     * 审核报名项目接口（根据项目id和购买人id）
     *
     * @param dto
     * @return
     */
    @PutMapping("/student-sign-up-apply/change")
    public AjaxResult updatePayOrder(@RequestBody PayOrderDto dto) {
        SysUser user = userUtils.getCurrentUser();

        StudentSignUpApply apply = new StudentSignUpApply();
        //当前用户是培训机构
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            apply.setTrainingOrganizationId(user.getTrainingOrganization().getId());
        } else if (UserTypeEnum.STUDENT.getValue().equals(user.getUserType())) {
            apply.setTrainingOrganizationId(user.getStudent().getId());
        } else {
            apply.setTrainingOrganizationId(dto.getTrainingOrganizationId());
        }
        apply.setProjectId(dto.getProjectId());
        apply.setStatus(dto.getStatus());
        applyService.updatePayOrder(apply);
        return AjaxResult.success();
    }


    /**
     * 上传支付凭证
     *
     * @param dto
     * @return
     */
    @PutMapping("/student-sign-up-apply/pay")
    public AjaxResult changePayOrder(@RequestBody PayOrderDto dto) {
        SysUser user = userUtils.getCurrentUser();

        //当前用户是培训机构
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            dto.setTrainingOrganizationId(user.getTrainingOrganization().getId());
            dto.setOrderType(RegistrationTypeEnum.TWO.getValue());
        } else if (UserTypeEnum.STUDENT.getValue().equals(user.getUserType())) {
            dto.setOrderType(RegistrationTypeEnum.ONE.getValue());
            dto.setTrainingOrganizationId(user.getStudent().getId());
        }
        AjaxResult result = applyService.changePayOrder(dto);
        return result;
    }

    /**
     * 补考
     *
     * @param dto
     * @return
     */
    @PutMapping("/student-sign-up-apply/makeupexam")
    public AjaxResult makeupExam(@RequestBody MakeUpExamDto dto) {
        SysUser user = userUtils.getCurrentUser();

        //当前用户是培训机构
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            dto.setTrainingOrganizationId(user.getTrainingOrganization().getId());
            dto.setRegistrationType(RegistrationTypeEnum.TWO.getValue());
        } else if (UserTypeEnum.STUDENT.getValue().equals(user.getUserType())) {
            dto.setTrainingOrganizationId(user.getStudent().getId());
            dto.setRegistrationType(RegistrationTypeEnum.ONE.getValue());
        }
        applyService.makeupExam(dto);
        return AjaxResult.success();
    }

    /**
     * 通过订单id修改审核状态
     *
     * @param apply
     * @return
     */
    @PutMapping("/student-sign-up-apply/examine")
    public AjaxResult updateByOrderId(@RequestBody StudentSignUpApply apply) {
        applyService.updateByOrderId(apply);
        return AjaxResult.success();
    }

    /**
     * 根据主键审核接口
     *
     * @param id
     * @param status
     * @return
     */
    @PutMapping("/student-sign-up-apply/{id}/{status}")
    public AjaxResult updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
        StudentSignUpApply apply = new StudentSignUpApply();
        apply.setId(id);
        apply.setStatus(status);
        applyService.updateStatus(apply);
        return AjaxResult.success();
    }

    /**
     * 根据主键批量退款接口
     *
     * @param dto
     * @return
     */
    @PutMapping("/sign-up-refund")
    public AjaxResult updatePayType(@RequestBody PayTypeDto dto) {
        if (dto.getIds().size() > 0) {
            for (int i = 0; i < dto.getIds().size(); i++) {
                StudentSignUpApply apply = new StudentSignUpApply();
                int re = applyService.updatePayType(dto.getPayType(), dto.getIds().get(i) ,dto.getRefundAudit());
                if (re == -1) {
                    return AjaxResult.error(-1, "考试前5天内不能退款");

                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询申请详情
     *
     * @param id
     * @return
     */
    @GetMapping("/student-sign-up-apply/{id}")
    public AjaxResult selectById(@PathVariable Integer id) {
        log.info("Rest request to find student-sign-up-apply by id:{}", id);
        StudentSignUpApplyVo result = applyService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 删除申请
     *
     * @param id
     * @return
     */
    @DeleteMapping("/student-sign-up-apply/{id}")
    public AjaxResult deleteById(@PathVariable Integer id) {
        log.info("Rest request to delete student-sign-up-apply by id:{}", id);
        int row = applyService.delete(id);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 分页查询申请
     *
     * @param dto
     * @return
     */
    @GetMapping("/student-sign-up-apply")
    public AjaxResult selectByParams(StudentSignUpApplyDto dto) {
        //PageHelper.startPage(dto.getPageable().getPageNum(), dto.getPageable().getPageSize());
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<StudentSignUpApplyVo> apply = applyService.selectByParams(dto);
        PageInfo<StudentSignUpApplyVo> result = new PageInfo<>(apply);
        return AjaxResult.success(result);
    }

    /**
     * 查询我的报名列表
     *
     * @param dto
     * @return
     */
    @GetMapping("/student-sign-up-apply-my")
    public AjaxResult selectBy(StudentSignUpApplyDto dto) {
        //PageHelper.startPage(dto.getPageable().getPageNum(), dto.getPageable().getPageSize());
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<StudentSignUpApplyVo> apply = applyService.selectByParams(dto);
        PageInfo<StudentSignUpApplyVo> result = new PageInfo<>(apply);
        return AjaxResult.success(result);
    }

    /**
     * 查询申请集合
     */
    @GetMapping("/student-sign-up-apply-list")
    public AjaxResult selectByParamsList(StudentSignUpApplyDto dto) {

        List<StudentSignUpApplyVo> result = applyService.selectByParams(dto);
        return AjaxResult.success(result);
    }

    /**
     * 准考证打印
     */
    @PostMapping("/student-sign-up-apply/certificate")
    public void downloadCerticate(HttpServletResponse response, @RequestBody StudentSignUpApply params) {

        applyService.downloadCerticate(response, params.getId());
        return;
    }

    /**
     * 查看准考证
     */
    @GetMapping("/student-sign-up-apply/certificate/{id}")
    public AjaxResult queryCerticate(@PathVariable Integer id) {

        CerticateVo result = applyService.queryCerticate(id);
        return AjaxResult.success(result);

    }

    /**
     * 根据准考证编号查询准考证信息
     */
    @GetMapping("/student-sign-up-apply/admission/{admissionTicket}")
    public AjaxResult queryByAdmissionTicket(@PathVariable String admissionTicket) {

        CerticateVo result = applyService.queryByAdmissionTicket(admissionTicket);
        if (result == null) {

            return AjaxResult.error(-1, "未查到该准考证号相关信息，请核实输入信息");
        }
        return AjaxResult.success(result);

    }

    /**
     * 导出报名信息
     */

    @GetMapping("/student-sign-up-apply-excel")
    public void downloadExcel(StudentSignUpApplyDto dto, HttpServletResponse response) {

        List<StudentSignUpApplyVo> list = applyService.selectByParams(dto);
        downloadExcel(list, response);
    }

    /**
     * 导出excel
     *
     * @param list
     * @param response
     */
    public void downloadExcel(List<StudentSignUpApplyVo> list, HttpServletResponse response) {
        String title = "报名信息表";
        Workbook workbook = writeDataToExcel(list);
        try {
            ExcelUtil.downloadExcel(response, workbook, title);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将数据写入excel
     *
     * @param list
     * @return
     */
    public Workbook writeDataToExcel(List<StudentSignUpApplyVo> list) {
        String[] titleList = {"购买人", "项目分类", "报名项目", "报名科目", "姓名", "性别", "身份证号", "联系电话", "报名时间", "审核状态"};
        InputStream is = Test.class.getClassLoader().getResourceAsStream("templates/studentApply.xlsx");
        //检查模板文件
        Workbook workbook = null;
        try {
            workbook = new XSSFWorkbook(is);
            if (workbook != null) {
                for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                    //获得当前sheet工作表
                    Sheet sheet = workbook.getSheetAt(sheetNum);
                    if (sheet == null) {
                        continue;
                    }
                    //获得当前sheet的结束行
                    int lastRowNum = sheet.getLastRowNum();
                    Row firstRow = sheet.getRow(lastRowNum - 1);
                    int columnNum = 0;
                    if (firstRow != null) {
                        columnNum = firstRow.getPhysicalNumberOfCells();
                    }
                    for (int j = 0; j < columnNum; j++) {
                        Cell cell = firstRow.getCell(j); //第1行,第j列
                        String cellValue = cell.getStringCellValue();
                        System.out.println(cellValue);
                    }
                    Row row = sheet.createRow(lastRowNum + 1);
                    //创建内容
                    Cell dataCell = null;
                    int count = 0;
                    for (int i = 0; i < list.size(); i++) {
                        row = sheet.createRow(lastRowNum + i + 1);
                        for (int j = 0; j < titleList.length; j++) {
                            dataCell = row.createCell(j);
                            if (j == 0) {
                                String value = list.get(i).getTrainingOrganizationName();
                                dataFormat(dataCell, value);
                            } else if (j == 1) {
                                String value = list.get(i).getClassifyName();
                                dataFormat(dataCell, value);
                            } else if (j == 2) {
                                String value = list.get(i).getProjectName();
                                dataFormat(dataCell, value);
                            } else if (j == 3) {
                                if (list.get(i).getSubjectType().equals(SubjectStatusEnum.ONE.getValue())) {
                                    String value = SubjectStatusEnum.ONE.getLabel();
                                    dataFormat(dataCell, value);
                                } else if (list.get(i).getSubjectType().equals(SubjectStatusEnum.TEO.getValue())) {
                                    String value = SubjectStatusEnum.TEO.getLabel();
                                    dataFormat(dataCell, value);
                                } else {
                                    String value = SubjectStatusEnum.THREE.getLabel();
                                    dataFormat(dataCell, value);
                                }
                            } else if (j == 4) {
                                String value = list.get(i).getName();
                                dataFormat(dataCell, value);
                            } else if (j == 5) {
                                if (list.get(i).getSex() == 1) {
                                    String value = "男";
                                    dataFormat(dataCell, value);
                                } else {
                                    String value = "女";
                                    dataFormat(dataCell, value);
                                }
                            } else if (j == 6) {
                                String value = list.get(i).getIdCard();
                                dataFormat(dataCell, value);
                            } else if (j == 7) {
                                String value = list.get(i).getTel();
                                dataFormat(dataCell, value);
                            } else if (j == 8) {
                                Date seconds = list.get(i).getCreateTime();
                                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String value = formatter.format(seconds);
                                dataFormat(dataCell, value);

                            } else if (j == 9) {
                                if (list.get(i).getStatus().equals(StudentSignUpApplyStatusEnum.FOUR.getValue())) {
                                    String value = StudentSignUpApplyStatusEnum.FOUR.getLabel();
                                    dataFormat(dataCell, value);
                                } else if (list.get(i).getStatus().equals(StudentSignUpApplyStatusEnum.THREE.getValue())) {
                                    String value = StudentSignUpApplyStatusEnum.THREE.getLabel();
                                    dataFormat(dataCell, value);
                                } else if (list.get(i).getStatus().equals(StudentSignUpApplyStatusEnum.FIVE.getValue())) {
                                    String value = StudentSignUpApplyStatusEnum.FIVE.getLabel();
                                    dataFormat(dataCell, value);
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

    /**
     * 单元格值格式化
     *
     * @param dataCell
     * @param obj
     */
    private static void dataFormat(Cell dataCell, Object obj) {
        if (obj == null) {
            dataCell.setCellValue("");
        } else {
            if (obj instanceof String) {
                dataCell.setCellValue((String) obj);
            } else if (obj instanceof Double) {
                dataCell.setCellValue((Double) obj);
            } else if (obj instanceof Float) {
                dataCell.setCellValue((Float) obj);
            } else if (obj instanceof Long) {
                dataCell.setCellValue((Long) obj);
            } else if (obj instanceof Boolean) {
                dataCell.setCellValue((Boolean) obj);
            } else if (obj instanceof Date) {
                Date d = (Date) obj;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String createDate = sdf.format(d);
                dataCell.setCellValue(createDate);
            }
        }
    }

}
